<?php
/**
 * @version		$Id: weblinks.php 8117 2007-07-20 13:37:22Z friesengeist $
 * @package		Joomla
 * @subpackage	Content
 * @copyright	Copyright (C) 2005 - 2007 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport('joomla.application.component.model');

/**
 * Weblinks Component Weblink Model
 *
 * @author	Johan Janssens <johan.janssens@joomla.org>
 * @package		Joomla
 * @subpackage	Content
 * @since 1.5
 */
class BookstoreModelStaff extends JModel
{
	/**
	 * Category ata array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Category total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */
	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;
		$this->db =& JFactory::getDBO();
		$cid = $cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		$id = JRequest::getVar('id', $cid[0], '', 'array');
		$this->setId((int)$id[0]);
		
		// Get the pagination request variables
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

	function setId($id)
	{
		// Set new article ID and wipe data
		$this->_id		= $id;
		$this->_article	= null;
	}

	function cleanISBN($input){
		if(is_array($input)){
			foreach($input as $key=>$value){
				//if(preg_match("/^[0-9][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-]/",$value) ){
					$input[$key]= preg_replace("/-/","",$value);
				//}//end if
			}//end foreach
		}else{
			$input = preg_replace("/-/","",$input);
		}//end if array
			
		return $input;
	}//end cleanISBN
	
	/**
	 * Method to get weblinks item data
	 *
	 * @access public
	 * @return array
	 */
	function getData($type = '')
	{
		// Lets load the content if it doesn't already exist
		//if (empty($this->_data))
	//	{
		if($type == 'detail'){
			$query = $this->_buildQuery($type);
			$this->_data = $this->_getList($query, '','');
		}else{
	//	//	if(!empty($query)){
				$query = $this->_buildQuery();
				$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
				//var_dump($query);
		//	}
		}
		//var_dump($this->_data);//$this->_id);//
		return $this->_data;
	}

	


	/**
	 * Method to get the total number of weblink items
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the weblinks
	 *
	 * @access public
	 * @return integer
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

	
	function _buildQuery($type = '')
	{
		if($type == 'detail'){
			$where = (empty($this->_id)) ? '' : ' WHERE a.id = '.$this->_id;
       		$query = ' SELECT a.*, cc.title AS category '
				. ' FROM #__staffselection AS a '
				. ' LEFT JOIN #__categories AS cc ON cc.id = a.catid '
				//. ' LEFT JOIN #__users AS u ON u.id = a.checked_out '
				. $where;
		
		}else{
		// Get the WHERE and ORDER BY clauses for the query
			global $mainframe, $option;
		//	$search				= $mainframe->getUserStateFromRequest( $option.'search',			'search',			'',				'string' );
	//	if(!empty($search)){
			$where		= $this->_buildContentWhere();
			$orderby	= $this->_buildContentOrderBy();
			$query = ' SELECT a.*, cc.title AS category '
				. ' FROM #__staffselection AS a '
				. ' LEFT JOIN #__categories AS cc ON cc.id = a.catid '
				//. ' LEFT JOIN #__users AS u ON u.id = a.checked_out '
				. $where
				. $orderby
			;
		//}
		}//end if $type
		
		return $query;
	}

	function _buildContentOrderBy()
	{
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'filter_order',		'filter_order',		'a.created',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'filter_order_Dir',	'filter_order_Dir',	'desc',				'word' );

		if ($filter_order == 'a.created'){
			$orderby 	= ' ORDER BY a.created '.$filter_order_Dir.', cc.title';
		} else {
			$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , a.created, cc.title';
		}

		return $orderby;
	}

	function _buildContentWhere()
	{
		global $mainframe, $option;

		$filter_state		= $mainframe->getUserStateFromRequest( $option.'filter_state',		'filter_state',		'',				'word' );
		$filter_catid		= $mainframe->getUserStateFromRequest( $option.'filter_catid',		'filter_catid',		0,				'int' );
		$filter_order		= $mainframe->getUserStateFromRequest( $option.'filter_order',		'filter_order',		'a.ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$search				= $mainframe->getUserStateFromRequest( $option.'search',			'search',			'',				'string' );
		$search				= JString::strtolower( $search );

		$where = array();

		if ($filter_catid > 0) {
			$where[] = 'a.catid = '.(int) $filter_catid;
		}
		if ($search) {
			$where[] = '(LOWER(a.title) LIKE '.$this->_db->Quote('%'.$search.'%').' OR LOWER(a.author) LIKE '.$this->_db->Quote('%'.$search.'%').")";
		}
		if ( $filter_state ) {
			if ( $filter_state == 'P' ) {
				$where[] = 'a.published = 1';
			} else if ($filter_state == 'U' ) {
				$where[] = 'a.published = 0';
			}
		}
		//$id = JRequest::getVar('id');
		//var_dump($id);
		if(!empty($this->_id)){
			//foreach($this->_id as $i){
				$where[] = 'a.id = '.$i;
			//}
		}
		$where 		= ( count( $where ) ? ' WHERE '. implode( ' AND ', $where ) : '' );

		return $where;
	}
	
		///////////////////////////////////////
	function saveContentPrep( &$data )
	{

		// Get submitted text from the request variables
		$description = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		// Clean text for xhtml transitional compliance
		jimport('joomla.filter.output');
		$description		= str_replace( '<br>', '<br />', $description );
		//$title = JRequest::getVar( 'title', '', 'post', 'string', JREQUEST_ALLOWRAW );
	//	$data['title']	= JOutputFilter::ampReplace($title);
		//$data['title'] = $this->JS_SpecialChars($data['title']);
		
		// Search for the {readmore} tag and split the text up accordingly.
		$tagPos	= JString::strpos( $description, '<hr id="system-readmore" />' );

		if ( $tagPos === false )
		{
			$data['introdescription']	= $description;
		} else
		{
			$data['introdescription']	= JString::substr($description, 0, $tagPos);
			$data['fulldescription']	= JString::substr($description, $tagPos + 27 );
		}

		return true;
		/**/
	}
		function getIndices(){
			$id = JRequest::getVar('id');
			if(!empty($id)){
				$query = "SELECT isbn from #__staffselectionindex WHERE selectionid = '".$id."'";
				$this->_indices = $this->_getList($query);
				return $this->indices;
			}//end if
		}//end getIndices
		
		
		function deleteIndices($id = ''){
			if(!empty($id) && is_array($id)){
				foreach($id as $i){
					$query = 'DELETE FROM #__staffselectionindex'
					. ' WHERE selectionid = '.$id
					;
					$this->db->setQuery( $query );
					if (!$this->db->query()) {
						return JError::raiseWarning( 500, $this->db->getErrorMsg());
					}//end if
				}//end foreach
			}elseif(is_string($id) && !empty($id)){
				$query = 'DELETE FROM #__staffselectionindex'
					. ' WHERE selectionid = '.$id
					;
					$this->db->setQuery( $query );
					if (!$this->db->query()) {
						return JError::raiseWarning( 500, $this->db->getErrorMsg());
					}//end if
			}//end if
		}//end deleteindices method
		
		function insertIndices($id, $isbnArray){
			if(is_array($isbnArray)){
			
				foreach ($isbnArray as $isbn)
				{
					// this check for the blank spaces in the select box that have been added for cosmetic reasons
					if (!empty($isbn)) {
						$set = 'isbn = '. $this->db->Quote($isbn);
						if( !empty($id) ){
							$set .= ', selectionid = '. $id;
						}
						// assign new module to menu item associations
						$query = 'INSERT INTO #__staffselectionindex'
						. ' SET selectionid = '.$id .', isbn = '. $this->db->Quote($isbn)
						//.' SET '. $set
						;
						$this->db->setQuery( $query );
						if (!$this->db->query()) {
							return JError::raiseWarning( 500, $this->db->getErrorMsg());
						}//end if query
					}//end if isbn
				}//end foreach
			}elseif(is_string($isbnArray) && !empty($isbnArray)){
				// assign new module to menu item associations
				$isbn = isbnArray;
				$set = 'isbn = '. $this->db->Quote($isbn);
						if( !empty($id) ){
							$set .= ', selectionid = '. $id;
						}
				$query = 'INSERT INTO #__staffselectionindex'
				. ' SET selectionid = '.$id .', isbn = '. $this->db->Quote($isbn)
				//.' SET '. $set
				;
				$this->db->setQuery( $query );
				if (!$this->db->query()) {
					return JError::raiseWarning( 500, $this->db->getErrorMsg());
				}//end if query
			}//end is_array
		}//end insertIndices method
		
		
		function store($data)
{
	//var_dump('row 306');
	//$user   =& JFactory::getUser();
	//$userid = $user->get('id');
   
    $row =& $this->getTable('staffselection');
	
	//var_dump('row 308');
   
	//$data['description'] = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
	//$data['title'] = JRequest::getVar( 'title', '', 'post', 'string', JREQUEST_ALLOWRAW );
	
  // 	$time = JRequest::getVar( 'start_time', '', 'post', 'array' );
	//$data['start_time'] = $this->time_selector($time);
	//$data['created_by']
	$params		= JRequest::getVar( 'params', '', 'post', 'array' );
		// Build parameter INI string
		if (is_array($params)){
			$txt = array();
			foreach ($params as $k => $v) {
				
				if( substr($k,0,4) == 'isbn'){
					$txt[] = "$k=".$this->cleanISBN($v);
				//	$this->insertIndices($data['id'],$v);
					$add_indices[] = $this->cleanISBN($v);
				}else{
					$txt[] = "$k=".$v;
				}
			}
			
			$data['params'] = implode("\n", $txt);
		}//end params is array
		
		if(is_array($data['meta'])){
			foreach ($data['meta'] as $k => $v) {
					$data[$k] = $v;
			}
		}//edn data-meta is array
		
	$user = & JFactory::getUser();
	$data['created_by']= $user->id;
		
	$this->saveContentPrep( $data );
	
//	$data['publish_up'] = date('Y-m-d G:i:s', time());
//	$data['publish_down'] = $data['start_date']." ".$data['start_time'];
	$data{'state'} = $data['published'];
	var_dump($data);
	if (!$row->bind($data)) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }
    // Make sure the hello record is valid
    if (!$row->check()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    // Store the web link table to the database
    if (!$row->store()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }
	
	if( empty($data['id']) ){
		$data['id'] = $this->_db->insertid();
		//var_dump($data['id']);
	}
	
	$this->deleteIndices($data['id']);
//	foreach($add_indices as $isbn_to_index){
//		$this->insertIndices($data['id'], $isbn_to_index);
	$this->insertIndices($data['id'], $add_indices);
//	}
	
    return true;
}
/*
	$row =& $this->getTable('staffselection');

    $data = JRequest::get( 'post' );
    // Bind the form fields to the hello table
    if (!$row->bind($data)) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    // Make sure the hello record is valid
    if (!$row->check()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    // Store the web link table to the database
    if (!$row->store()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    return true;
}
*/
	function delete($cid){
		//var_dump('removea');
		$row =& $this->getTable('staffselection');
		//var_dump('removeb');
		if( is_array($cid) ){
			foreach($cid as $id){
				if( !$row->delete($id) ) {
					return false;
				}
				$this->deleteIndices($data['id']);
			}//end foreach loop
			return true;
		}else{
			//what, it should be an array
			$status = $row->delete($id);
			$this->deleteIndices($data['id']);
			return $status;
		}//end if cid is array
	}//end delete method
	
	/**
	 * Method to (un)publish a event
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__staffselection'
				. ' SET state = ' . intval( $publish )
				. ' WHERE id IN ( '.$cids.' )'
				//. ' AND ( checked_out = 0 OR ( checked_out = ' .$user->get('id'). ' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}//end publish method
}//end model class
?>
